//
//  SWLargeCollageViewController.swift
//  ChildStory
//  大长图
//  Created by linhan on 2017/1/6.
//  Copyright © 2017年 Aiya. All rights reserved.
//

import Foundation
class SWLargeCollageViewController: SWBaseViewController,SWPhotoViewerDelegate
{
    private struct PVPhoto:SWPVPhoto
    {
        var object: Any?
        var largeImage:UIImage?
        var largeImageURL:String?
        var thumbImage:UIImage?
        init()
        {
            
        }
    }
    
    var photos:[SWALPhoto] = []
    
    private var _image:UIImage?
    
    private var _photoViewer:SWPhotoViewer?
    lazy private var _topBar:UIView = UIView()
    lazy private var _bottomBar:UIView = UIView()
    lazy private var _loadingView = UIActivityIndicatorView(activityIndicatorStyle: .white)
    
    deinit
    {
        trace("DEINIT SWLargeCollageViewController")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    override var prefersNavigationBarHidden: Bool{
        return true
    }
    
    //关闭
    func close()
    {
        dismiss(animated: true, completion: nil)
    }
    
    private func setup()
    {
        automaticallyAdjustsScrollViewInsets = false
        view.backgroundColor = UIColor.black
        
        
        let photoViewer:SWPhotoViewer = SWPhotoViewer(frame: view.frame)
        photoViewer.registerClassForPhotoFetcher(SWPhotoViewerAssetFetcher.self)
        photoViewer.delegate = self
        view.addSubview(photoViewer)
        _photoViewer = photoViewer
        
        
        
        let topBar:UIView = UIView()
        topBar.backgroundColor = UIColor(white: 0, alpha: 0.5)
        topBar.frame = CGRectMake(0, 0, view.width, 64)
        view.addSubview(topBar)
        _topBar = topBar
        
        let backBtn:UIButton = UIButton(type: .custom)
        backBtn.setImage(UIImage(named:"global_btn_back"), for: .normal)
        backBtn.sizeToTouchEasy()
        backBtn.center = CGPointMake(15, 34)
        backBtn.addTarget(self, action: #selector(backBtnTapped), for: .touchUpInside)
        topBar.addSubview(backBtn)
        
        let closeBtn:UIButton = UIButton(type: .system)
        closeBtn.setTitle("X", for: .normal)
        closeBtn.sizeToTouchEasy()
        closeBtn.frame = CGRectMake(topBar.width - closeBtn.width - 15, topBar.height * 0.5, closeBtn.width, closeBtn.height)
        closeBtn.addTarget(self, action: #selector(closeBtnTapped), for: .touchUpInside)
        topBar.addSubview(closeBtn)
        
        let bottomBarHeight:CGFloat = 40
        let bottomBar:UIView = UIView()
        bottomBar.backgroundColor = UIColor(white: 0, alpha: 0.5)
        bottomBar.frame = CGRectMake(0, view.height - bottomBarHeight, view.width, bottomBarHeight)
        view.addSubview(bottomBar)
        _bottomBar = bottomBar
        
        let shareBtn:UIButton = UIButton(type: .system)
        shareBtn.setTitle("分享", for: .normal)
        shareBtn.sizeToFit()
        shareBtn.frame = CGRectMake(bottomBar.width - shareBtn.width - 15, bottomBar.height * 0.5, shareBtn.width, shareBtn.height)
        shareBtn.addTarget(self, action: #selector(shareBtnTapped), for: .touchUpInside)
        _bottomBar.addSubview(shareBtn)
        
        if photos.count > 0
        {
            _loadingView.center = view.center
            _loadingView.startAnimating()
            generate()
        }
    }
    
    private func generate()
    {
        var options = SWALPhotoRequestOptions()
        options.targetSize = CGSizeMake(750, 2000)
        SWAssetsLibraryHelper.shared().fetchOriginImage(photos: photos, completeCallback: {[weak self] results in
            
            let images:[UIImage] = results.flatMap({$0.image})
            DispatchQueue.globalDefault.async {
                self?._image = self?.combine(images: images)
                DispatchQueue.main.async {
                    self?._loadingView.stopAnimating()
                    self?._photoViewer?.reloadData()
                    self?._photoViewer?.showFromIndex(0, rect: nil)
                }
            }
            
        }, options: options)
    }
    
    //合并
    private func combine(images:[UIImage]) -> UIImage?
    {
        let containerWidth:CGFloat = 750
        let Grid:CGFloat = 20
        var data:[(image:UIImage, rect:CGRect)] = []
        
        var lastY:CGFloat = 0
        for (i,image) in images.enumerated()
        {
            let size = image.size
            let ratio:CGFloat = containerWidth / size.width
            let imageHeight:CGFloat = size.height * ratio
            let rect:CGRect = CGRectMake(0, i > 0 ? lastY + Grid : lastY, containerWidth, imageHeight)
            lastY = rect.bottom
            data.append((image: image, rect:rect))
            //print("rect:", rect)
        }
        
        //创建白色画布
        let size:CGSize = CGSize(width: containerWidth, height: lastY)
        UIGraphicsBeginImageContextWithOptions(size, true, 1)
        UIColor.white.setFill()
        UIRectFill(CGRect(origin: CGPoint.zero, size: size))
        
        for info in data
        {
            info.image.draw(in: info.rect)
        }
        let result:UIImage? = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return result
    }
    
    
    //MARK ============================================================================================
    //==============================        SWPhotoViewerDelegate       ===============================
    //=================================================================================================
    
    //照片总数
    func numberOfPhotosInPhotoViewer(_ photoViewer: SWPhotoViewer) -> Int
    {
        return 1
    }
    
    //对应位置的照片
    func photoViewer(_ photoViewer: SWPhotoViewer, photoAtIndex index: Int) -> SWPVPhoto?
    {
        var photo:PVPhoto = PVPhoto()
        photo.largeImage = _image
        return photo
    }
    
    func photoViewer(_ photoViewer: SWPhotoViewer, didSingleTapAtIndex index: Int)
    {
        //_toolbarHidden = !_toolbarHidden
    }
    
    
    @objc private func backBtnTapped()
    {
        navigationController?.popViewController(animated: true)
    }
    
    @objc private func shareBtnTapped()
    {
        SWSharePresenter.instance.show {[weak self] action in
            let channel = SWShareAction.getShareChannelFormAction(action: action)
            if let image = self?._image{
                SWShareManager.sharedManager().share(image: image,channel: channel)
            }
            
        }
    }
    
    @objc private func closeBtnTapped()
    {
        close()
    }
    
    
    
    
    
    
}
